package com.youi.interceptor;


import com.youi.common.Common;
import com.youi.common.SessionKey;
import com.youi.entity.Sysuser;
import com.youi.exception.BusinessException;
import com.youi.manage.HttpSessionManage;
import com.youi.util.CommonInfoUtil;
import com.youi.util.JedisUtils;
import com.youi.util.LogUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 会话拦截器
 *
 * @author Administrator
 */
@Component
public class SessionInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        LogUtil.Debug("======================");
        LogUtil.Debug("请求url===" + url);
        LogUtil.Debug("会话ID===" + HttpSessionManage.getSessionId(request));

        /**
         * 登陆拦截
         */
        if (url.contains(Common.SYSUSERPMS)) {
            Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
            if (sysuser == null) {
                //再从redis中获取用户会话信息,如果没有再抛异常
                String sessionId = HttpSessionManage.getSessionId(request);
                sysuser = JedisUtils.getObject(SessionKey.SYSUSER + ":" + sessionId, Sysuser.class);
                if (sysuser == null) {
                    throw new BusinessException(CommonInfoUtil.NOLOGIN, "用户未登录");
                }
                HttpSessionManage.setAttribute(request, SessionKey.SYSUSER, sysuser);
            }

            if (url.contains(Common.ADMININFO)) {
                if (sysuser.getRole() > 1) {
                    throw new BusinessException(CommonInfoUtil.NOOPPMS, "无操作权限");
                }
            }
        }
        return true;
    }

    /**
     * 拦截器结束请求后执行
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    public static void main(String[] args) {
        String url = "http://127.0.0.1:8088/Nailart/storeuserGetJsonInfo/storeUserGetUser.do?openid=3";
        System.err.println(url.contains(Common.USERPMS));
    }
}
